﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts;
using Web.Framework.Mapper;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class PaisEdit : BasePage
    {
        public Pais paisCurrent
        {
            get
            {
                return (Pais)ViewState["ptoDeVentaCurrent"];
            }
            set
            {
                ViewState["ptoDeVentaCurrent"] = value;
            }
        }

        public bool esNuevo
        {
            get
            {
                return (bool)ViewState["esNuevo"];
            }
            set
            {
                ViewState["esNuevo"] = value;
            }
        }

        LinkButton nuevaProvinciaButton = new LinkButton();
        LinkButton eliminarButton = new LinkButton();
        private List<LinkButton> actionButtons = new List<LinkButton>();
        LinkButton guardarButton = new LinkButton();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
           
            guardarButton.ID = "BoCommandGuardar";
            guardarButton.Text = LocalizationProvider.Instance["Bo.Command.Guardar"];
            guardarButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(guardarButton);

            LinkButton volverButton = new LinkButton();
            SetJavascriptForClientClickDirtyChech(volverButton);
            volverButton.ID = "BoCommandVolver";
            volverButton.CausesValidation = false;
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(lnkCancelar_Click);
            actionButtons.Add(volverButton);
            
            SetJavascriptForClientClickDirtyChech(nuevaProvinciaButton);
            nuevaProvinciaButton.ID = "BoCommandNuevaProvincia";
            nuevaProvinciaButton.CausesValidation = false;
            nuevaProvinciaButton.Text = LocalizationProvider.Instance["Bo.Pais.ActionMenu.NuevaProvincia"];
            nuevaProvinciaButton.Click += new EventHandler(nuevaProvinciaButton_Click);
            actionButtons.Add(nuevaProvinciaButton);

            eliminarButton.ID = "BoCommandEliminar";
            eliminarButton.CausesValidation = false;
            eliminarButton.Text = LocalizationProvider.Instance["Bo.Command.Eliminar"];
            eliminarButton.Click += new EventHandler(eliminarButton_Click);
            actionButtons.Add(eliminarButton);

            base.LoadContextActions(actionButtons);
        }

        private void eliminarButton_Click(object sender, EventArgs e)
        {
            try
            {
                WebServiceHelper.EliminarPaisDto(paisCurrent.Id);
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPaisList + string.Format("?{0}=1", MiscClass.QueryShowDeleted), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void nuevaProvinciaButton_Click(object sender, EventArgs e)
        {
            SetThisPageToGoBack();
            this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlProvinciaEdit + "?PaisId={0}", paisCurrent.Id), true);
        }

        protected void Page_Load(object sender, EventArgs e)
        {          
            try
            {
                HasPermissionToSeeMe(CrmSecurity.COUNTRY_SEARCH, CrmSecurity.COUNTRY_MANAGE, CrmSecurity.PROVINCE_SEARCH, CrmSecurity.PROVINCE_MANAGE);

                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["Id"] == null)
                    {
                        NuevoPais();                        
                    }
                    else
                    {
                        var search = new PaisSearch() { Id = Convert.ToInt32(this.Request.QueryString["Id"]) };
                        search.LoadProvincia = true;
                        paisCurrent = WebServiceHelper.GetPaisesDto(search).First();
                        esNuevo = false;
                    }

                    this.NavigationContext.UrlToGoBack = string.Empty;

                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void NuevoPais()
        {
            paisCurrent = new Pais();
            esNuevo = true;
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            if (!esNuevo)
            {
                this.txtId.ReadOnly = true;
                this.txtId.CssClass += " readonly";
                nuevaProvinciaButton.Visible = HasPermissionFor(CrmSecurity.COUNTRY_MANAGE);
                eliminarButton.Visible = HasPermissionFor(CrmSecurity.COUNTRY_MANAGE);
                guardarButton.Visible =
                lnkGuardar.Visible = HasPermissionFor(CrmSecurity.COUNTRY_MANAGE);
                SetJavascriptForDeleteRecord(eliminarButton, paisCurrent.Nombre);

                this.Grid.Columns[0].Visible = HasPermissionFor(CrmSecurity.COUNTRY_MANAGE) || HasPermissionFor(CrmSecurity.PROVINCE_MANAGE) || HasPermissionFor(CrmSecurity.COUNTRY_SEARCH) || HasPermissionFor(CrmSecurity.PROVINCE_SEARCH);
                this.Grid.Columns[1].Visible = HasPermissionFor(CrmSecurity.PROVINCE_MANAGE) || HasPermissionFor(CrmSecurity.COUNTRY_MANAGE);
            }
            else
            {
                nuevaProvinciaButton.Visible = false;
                eliminarButton.Visible = false;
                guardarButton.Visible =
                lnkGuardar.Visible = HasPermissionFor(CrmSecurity.COUNTRY_MANAGE);
            }            
        }

        private void SetThisPageToGoBack()
        {
            this.NavigationContext.UrlToGoBack = this.Request.Url.AbsoluteUri;
        }

        private void Bind()
        {
            EntityMapper.Map(paisCurrent, this);
            BindGrid();
            if (esNuevo)
            {
                this.txtId.Text = string.Empty;
            }
        }

        private void BindGrid()
        {
            this.Grid.DataSource = paisCurrent.Provincias;
            this.Grid.DataBind();
        }

        private void SetData()
        {
            EntityMapper.Map(this, paisCurrent);
        }

        private void Save()
        {
            paisCurrent = WebServiceHelper.SavePaisDto(paisCurrent);
            esNuevo = false;
            ClearPaises(HttpContext.Current);
        }

        private void Validar()
        {
            // TODO
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Provincia provincia = (Provincia)e.Row.DataItem;

                    e.Row.Cells[0].Attributes.Add("title", "Editar");
                    e.Row.Cells[1].Attributes.Add("title", "Eliminar");

                    ImageButton btnEditarCtrl = (ImageButton)e.Row.FindControl("btnEditar");
                    SetJavascriptForClientClickDirtyChech(btnEditarCtrl);

                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, provincia.Nombre);                    
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int provinciaId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    SetThisPageToGoBack();
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlProvinciaEdit + "?Id={0}", provinciaId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int provinciaId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.EliminarProvinciaDto(provinciaId);
                    var provincia = paisCurrent.Provincias.Where(p => p.Id == provinciaId).Single();
                    paisCurrent.Provincias.Remove(provincia);
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Validar();
                SetData();
                Save();
                Bind();
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPaisList, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.Grid.AllowPaging;
                this.Grid.AllowPaging = false;

                BindGrid();

                GridViewExportExcelUtil.Export("Provincias.xls", this.Grid, 0, 1);

                this.Grid.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}